package sysService

import (
	"fmt"
	"gitee.com/jokces/kit/enum"
	"gitee.com/jokces/kit/global"
	sysModel "gitee.com/jokces/kit/global/admin/model"
	"log"
	"os"
	"strings"
)

func New() {
	sqlInit()

	log.Printf("start init dic data:%v !\n", len(enum.Dic))
	r := make([]*sysModel.SysDic, 0)
	if err := global.GetDb().Where("`status` = 1").Find(&r); err != nil {
		log.Printf("init dic data error:%v !\n", len(enum.Dic))
		return
	}
	for _, dic := range r {
		enum.Dic[dic.UniqueKey] = dic.Value
	}
	log.Printf("load dic data success:%v !\n", len(enum.Dic))
}

func sqlInit() {
	log.Printf("start init system data !\n")
	vo := &sysModel.SysParam{}
	exist, err := global.GetDb().Where("`key` = ?", "SqlInit").Get(vo)
	if err != nil {
		panic("init system data err: \n" + err.Error())
		return
	}
	if !exist {
		vo.Key = "SqlInit"
		vo.Name = "init_system_data"
		vo.Memo = "init system data"
		vo.Value = "0"
		if row, err := global.GetDb().Insert(vo); err != nil {
			panic("init system lock insert to 0 error: \n" + err.Error())
			return
		} else if row != 1 {
			panic("init system lock insert to 0 error: \n" + err.Error())
			return
		}
	}
	if exist && vo.Value == "1" {
		fmt.Printf("init system data success....!\n")
		return
	}

	sqls, err := os.ReadFile("./configs/init.sql") //采用相对路径的处理
	if err != nil {
		panic("init sql error:" + err.Error())
		return
	}
	list := strings.Split(strings.TrimSpace(string(sqls)), ";")
	for _, sql := range list {
		sql = strings.TrimSpace(sql)
		if sql == "" {
			continue
		}
		if _, err := global.GetDb().Exec(sql); err != nil {
			panic("init sql error:" + err.Error())
			return
		}
	}

	_, err = global.GetDb().Where("`key` = ?", "SqlInit").Update(&sysModel.SysParam{Value: "1"})
	if err != nil {
		panic("init system lock update to 1 error: " + err.Error())
		return
	}
	fmt.Printf("init system data success....!\n")
}
